package com.t365.qmm.servlet;

import com.t365.qmm.pojo.Cart;
import com.t365.qmm.pojo.Goods;
import com.t365.qmm.pojo.User;
import com.t365.qmm.service.CartService;
import com.t365.qmm.service.GoodsService;
import com.t365.qmm.service.impl.CartServiceImpl;
import com.t365.qmm.service.impl.GoodsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Jane
 * @date 2024-02-29 17:18
 */

@WebServlet("/CartServlet")
public class CartServlet extends HttpServlet {

    CartService cartService = new CartServiceImpl();
    GoodsService goodsService = new GoodsServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("--------------------------------CartServlet");
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");

        HttpSession session = req.getSession();

        //处理购车
        //User user =(User) session.getAttribute("loginUser");
        Integer userId =49;
        //从jsp中点击按钮传递过来的数量
        Integer goodsId =Integer.parseInt(req.getParameter("goodsId"));
            Integer quantity =Integer.parseInt(req.getParameter("quantity"));

        Map<String,Object> maps = new HashMap<String,Object>();
        maps.put("userId",userId);
        //判断商品xxx是否在该用户的购物车中
        maps.put("goodsId",goodsId);
        List<Cart> cartList = cartService.getCartsByCondition(maps);//获取商品信息
        if (null!=cartList && cartList.size()>0){//有
            Cart cart =cartList.get(0);
            cart.setQuantity(cart.getQuantity()+quantity);
            cartService.updateByPrimaryKey(cart);//更新数量
        }else{//无
            Cart cart=new Cart();
            cart.setUserid(userId);
            cart.setGoodsId(goodsId);

            //获取商品信息
            Goods goods =goodsService.selectByPrimaryKey(Long.valueOf(goodsId));

            cart.setGoodsName(goods.getGoodsName());
            cart.setQuantity(quantity);
            cart.setPrice(goods.getPrice());
            cart.setCreatedby(userId);
            cartService.insert(cart);

        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
